#!/bin/bash
# Special thank to Shiroko, he give me the insight of coding in proper way

################################# Here we import our tools
source /opt/bashimport/sbs-utils.bashimport
source /opt/bashimport/sbs-build-helper.bashimport

if [ "$1" = "amd64" ] || [ "$1" = "x64" ];then
ARCH="amd64"
ARCH_ANOTHERWAY="-amd64"
ARCH_STORE_PATH="amd64-store"
DEBIAN_MULTIARCH="x86_64-linux-gnu"
elif [ "$1" = "arm64" ] || [ "$1" = "arm" ];then
ARCH="arm64"
ARCH_ANOTHERWAY="-aarch64"
ARCH_STORE_PATH="arm64-store"
DEBIAN_MULTIARCH="aarch64-linux-gnu"
elif [ "$1" = "loong64" ];then
ARCH="loong64"
ARCH_ANOTHERWAY="-loong64"
ARCH_STORE_PATH="loong64-store"
else
log.error "Err:Invalid Architecture"
exit 1
fi

################################# Here we set the configs
REALPATH=`realpath $0`
HERE_PATH=`dirname $REALPATH`
REPO_PATH="${REPO_PATH:-/root/store-dir/}"
WORKDIR=`mktemp -d`


PKG_NAME="additional-base-lib"
APP_NAME="附加基础库 Additional Base Lib"
SOURCE_LIST_FILE=""
GITHUB_REPO=""
VERSION="" #Here we use other way to get version so do not write here
TAGS="ubuntu;deepin;uos;debian;community"
CATAGORY="tools" #https://gitee.com/deepin-community-store/spark-store/blob/dev/DOCS/spk-doc.md
DETAIL="内置glibc和libstdc++\n其实原理还是我们最爱的bwrap，创建一个容器把libc和ld.so替换掉，就这么简单（bwrap真是为大家节约了不少生命）。此外用了一点小技巧让大家仍然可以自己\n设置LD_LIBRARY_PATH变量来寻找自己安装的动态库。选用的glibc和libstdc++是从debian bookworm（debian 12，目前是测试版）上下载的，支持到GLIBC_2.36、GLIBCXX_3.4.30。\n安装：下载解压得到deb包，打开终端，输入 sudo apt install ，输入空格后在文件管理器里用鼠标按住deb包拖拽过去，然后按回车。\n使用：安装好了后，在终端运行不兼容的软件时，只需要在前面加上ablrun和空格就可以了。ablrun [命令]\n删除：sudo apt remove additional-base-lib\n注意事项：\n1、所有gcc库中我只加入了libstdc++（毕竟比较常用）。如果需要其他比如objective-c，fortran，d等语言的标准库，可以留言\n2、应该能在其他基于debian的发行版上运行，但是我还没测试\n3、由于包括的库比较少，只能解决部分兼容问题。但是通过学习，大家能解决所有常见问题。（可以看我之前的帖子：https://bbs.deepin.org/post/256081）\n4、不能保证程序没有故障，各位需要为自己系统的安全负责" # This should be written as json format
MAINTAINER="shenmo <shenmo@spark-app.store>"
HOMEPAGE="https://gitee.com/spark-store-project/additional-base-lib"

STORE_APP_PATH="${REPO_PATH}/${ARCH_STORE_PATH}/${CATAGORY}/${PKG_NAME}/"
################################# Fill the variables below only if you use write_control function

SECTION=""
PRIORITY=""
DEPENDS=""
DESCRIPTION_SHORT=""
DESCRIPTION_LONG=""
PROVIDES=""
REPLACES=""
RECOMMENDS=""




function prepare(){
#    aptss_get_update
    ABL_VERSION="9"
    PKG_VER_APTSS=`get_version_from_source_list_file ${PKG_NAME}:${ARCH} /opt/durapps/spark-store/bin/apt-fast-conf/sources.list.d/sparkstore${ARCH_ANOTHERWAY}.list`
    LINK=$(curl -s https://packages.debian.org/sid/${ARCH}/libc-bin/download | grep -o "http://ftp.cn.debian.org/debian/pool/main/g/glibc/libc-bin_.*_${ARCH}.deb")
    version=$(echo "$LINK" | grep -oP '_\K\d+\.\d+-\d+(?=_)')
    PKG_VER_UPSTREAM="${version%%_*}-${ABL_VERSION}" 
    compare_version ${PKG_VER_APTSS} ${PKG_VER_UPSTREAM}
    # Compare version will also give the value to $VERSION
    # Now we should have the $VERSION 
    if [ -e $VERSION ];then
    log.error "VERSION is empty. This should not happen! exit."
    exit
    fi
}




function build(){



pushd $WORKDIR

LIBC6_DOWNLOAD_URL=$(curl -s https://packages.debian.org/sid/${ARCH}/libc6/download | grep -o "http://ftp.cn.debian.org/debian/pool/main/g/glibc/libc6_.*_${ARCH}.deb")
LIBC_BIN_DOWNLOAD_URL=$(curl -s https://packages.debian.org/sid/${ARCH}/libc-bin/download | grep -o "http://ftp.cn.debian.org/debian/pool/main/g/glibc/libc-bin_.*_${ARCH}.deb")
LIBSTDCxx6_DOWNLOAD_URL=$(curl -s https://packages.debian.org/sid/${ARCH}/libstdc++6/download | grep -o "http://ftp.cn.debian.org/debian/.*_${ARCH}.deb")

ABL_VERSION=9

check(){
    if [ "$1" != 0 ]
    then
        echo "Error"
        exit
    fi
}


echo "download packages:"
mkdir ./downloads
echo "download libc6..."
wget "$LIBC6_DOWNLOAD_URL" -c -O ./downloads/libc6.deb
check $?
echo "download libc-bin..."
wget "$LIBC_BIN_DOWNLOAD_URL" -c -O ./downloads/libc-bin.deb
check $?
echo "download libstdc++6..."
wget "$LIBSTDCxx6_DOWNLOAD_URL" -c -O ./downloads/libstdc++6.deb
check $?

echo
echo "extract packages:"
echo "extract libc6..."
dpkg -x ./downloads/libc6.deb ./downloads/libc6
check $?
dpkg -e ./downloads/libc6.deb ./downloads/libc6/DEBIAN
check $?
echo "extract libc-bin..."
dpkg -x ./downloads/libc-bin.deb ./downloads/libc-bin
check $?
dpkg -e ./downloads/libc-bin.deb ./downloads/libc-bin/DEBIAN
check $?
echo "extract libstdc++6..."
dpkg -x ./downloads/libstdc++6.deb ./downloads/libstdc++6
check $?
dpkg -e ./downloads/libstdc++6.deb ./downloads/libstdc++6/DEBIAN
check $?

echo
echo "check packages:"
echo "check version libc6==libc-bin"
LIBC6_VERSION=`cat ./downloads/libc6/DEBIAN/control | grep "^Version: .*"`
check $?
LIBC6_VERSION=${LIBC6_VERSION:9}
LIBC_BIN_VERSION=`cat ./downloads/libc-bin/DEBIAN/control | grep "^Version: .*"`
check $?
LIBC_BIN_VERSION=${LIBC_BIN_VERSION:9}
LIBSTDCxx6_VERSION=`cat ./downloads/libstdc++6/DEBIAN/control | grep "^Version: .*"`
check $?
LIBSTDCxx6_VERSION=${LIBSTDCxx6_VERSION:9}

echo "$LIBC6_VERSION==$LIBC_BIN_VERSION"
[ "$LIBC6_VERSION" = "$LIBC_BIN_VERSION" ]
check $?

echo "check arch libc6==libc-bin"
LIBC6_ARCH=`cat ./downloads/libc6/DEBIAN/control | grep "^Architecture: .*"`
check $?
LIBC6_ARCH=${LIBC6_ARCH:14}
LIBC_BIN_ARCH=`cat ./downloads/libc-bin/DEBIAN/control | grep "^Architecture: .*"`
check $?
LIBC_BIN_ARCH=${LIBC_BIN_ARCH:14}

echo "$LIBC6_ARCH==$LIBC_BIN_ARCH"
[ "$LIBC6_ARCH" = "$LIBC_BIN_ARCH" ]
check $?

echo "check arch libc6==libstdc++6"
LIBSTDCxx6_ARCH=`cat ./downloads/libstdc++6/DEBIAN/control | grep "^Architecture: .*"`
check $?
LIBSTDCxx6_ARCH=${LIBSTDCxx6_ARCH:14}

echo "$LIBC6_ARCH==$LIBSTDCxx6_ARCH"
[ "$LIBC6_ARCH" = "$LIBSTDCxx6_ARCH" ]
check $?

echo
echo "collect information:"
echo "glibc version:"
GLIBC_VERSION=$LIBC6_VERSION
echo "$GLIBC_VERSION"

echo "deb package architecture:"
DEBIAN_DEB_ARCH=$LIBC6_ARCH
echo "$DEBIAN_DEB_ARCH"

echo "debian multiarch directory name:"


echo "check usrmerge status:":
if [ -d "./downloads/libc6/lib" ]
then
  LIBC_LIB_DIR=""
  echo "not usrmerge"
else
  LIBC_LIB_DIR="usr/"
  echo "usrmerge"
fi

echo "ld.so location:"
LD_SO_LOCATION=`patchelf --print-interpreter "./downloads/libc6/${LIBC_LIB_DIR}lib/${DEBIAN_MULTIARCH}/libc.so.6"`
check $?
echo "$LD_SO_LOCATION"

echo
echo "build package directories..."
mkdir ./deb-contents
mkdir ./deb-contents/DEBIAN
mkdir ./deb-contents/usr
mkdir ./deb-contents/usr/bin
mkdir ./deb-contents/usr/lib
mkdir "./deb-contents/usr/lib/$DEBIAN_MULTIARCH"

echo
echo "gather files:"

echo "generate ablrun script..."
echo "#!/bin/bash" > ./deb-contents/usr/bin/ablrun
echo "ABL_TARGET_LD_SO_PATH=$LD_SO_LOCATION" >> ./deb-contents/usr/bin/ablrun
echo "ABL_DIR_PREFIX=lib/$DEBIAN_MULTIARCH" >> ./deb-contents/usr/bin/ablrun
cat ${HERE_PATH}/scripts/ablrun_part >> ./deb-contents/usr/bin/ablrun
check $?

echo "chmod..."
chmod a+x ./deb-contents/usr/bin/*
check $?

rooted_readlink(){
    rrl_result=$1
    rrl_root=$2
    while [ -h "$rrl_result"  ]
    do
        rrl_result=`readlink "$rrl_result"`
        if [ "${rrl_result:0:1}" == "/" ]
        then
            rrl_result="$rrl_root/$rrl_result"
        else
            rrl_result=`dirname "$1"`"/$rrl_result"
        fi
    done
    echo -n "$rrl_result"
}

echo "copy many libc6 components..."
cp -r "./downloads/libc6/${LIBC_LIB_DIR}lib/${DEBIAN_MULTIARCH}/" "./deb-contents/usr/lib/${DEBIAN_MULTIARCH}/additional-base-lib"
check $?

echo "copy ld.so..."
mkdir --parents "./deb-contents/usr/lib/${DEBIAN_MULTIARCH}/additional-base-lib/$LD_SO_LOCATION"
rm -d "./deb-contents/usr/lib/${DEBIAN_MULTIARCH}/additional-base-lib/$LD_SO_LOCATION"
cp `rooted_readlink "./downloads/libc6/${LIBC_LIB_DIR}${LD_SO_LOCATION}" "./downloads/libc6"` "./deb-contents/usr/lib/${DEBIAN_MULTIARCH}/additional-base-lib/$LD_SO_LOCATION"
check $?

echo "copy ldd script..."
cp "./downloads/libc-bin/usr/bin/ldd" "./deb-contents/usr/lib/${DEBIAN_MULTIARCH}/additional-base-lib/ldd"
check $?

echo "copy libstdc++..."
cp `rooted_readlink ./downloads/libstdc++6/usr/lib/${DEBIAN_MULTIARCH}/libstdc++.so.6 ./downloads/libstdc++6/` "./deb-contents/usr/lib/${DEBIAN_MULTIARCH}/additional-base-lib/libstdc++.so.6"
check $?

echo "calculate file size..."
DEB_INSTALL_SIZE=(`du -s ./deb-contents/`)

echo
echo "create control file..."
echo "Package: additional-base-lib" >> ./deb-contents/DEBIAN/control
echo "Version: $GLIBC_VERSION-$ABL_VERSION" >> ./deb-contents/DEBIAN/control
echo "Section: utils" >> ./deb-contents/DEBIAN/control
echo "Priority: optional" >> ./deb-contents/DEBIAN/control
echo "Installed-Size: ${DEB_INSTALL_SIZE[@]:0:1}" >> ./deb-contents/DEBIAN/control
echo "Architecture: $DEBIAN_DEB_ARCH" >> ./deb-contents/DEBIAN/control
echo "Maintainer: CongTianKong" >> ./deb-contents/DEBIAN/control
echo "Depends: bubblewrap, bash, coreutils" >> ./deb-contents/DEBIAN/control
echo "Suggests: shared-mime-info, xdg-utils" >> ./deb-contents/DEBIAN/control
echo "Homepage: https://gitee.com/deepin-community-store/additional-base-lib" >> ./deb-contents/DEBIAN/control
echo "Description: A script to run programs with newer libc." >> ./deb-contents/DEBIAN/control
echo " package built with make-deb.sh from additional-base-lib project." >> ./deb-contents/DEBIAN/control
echo " libc6 download URL: $LIBC6_DOWNLOAD_URL" >> ./deb-contents/DEBIAN/control
echo " libc-bin download URL: $LIBC_BIN_DOWNLOAD_URL" >> ./deb-contents/DEBIAN/control
echo " libstdc++6 download URL: $LIBSTDCxx6_DOWNLOAD_URL" >> ./deb-contents/DEBIAN/control

echo >> ./deb-contents/DEBIAN/control
check $?

mkdir -p ./deb-contents/usr/lib/sysctl.d/

cat > ./deb-contents/usr/lib/sysctl.d/additional-base-lib.conf << 'EOF'

# ACE app runs in a container, need privileges within user namespace, so we need to set it
kernel.unprivileged_userns_clone=1
# Ubuntu 24.04 has more limitation on unprivileged user namespace,so we have to disable them.
# refer to https://ubuntu.com/blog/ubuntu-23-10-restricted-unprivileged-user-namespaces
kernel.apparmor_restrict_unprivileged_unconfined=0
kernel.apparmor_restrict_unprivileged_userns=0

EOF
cat > ./deb-contents/DEBIAN/postinst << 'EOF'
#!/bin/bash
if [ -f /usr/lib/sysctl.d/additional-base-lib.conf ];then
   sysctl -p /usr/lib/sysctl.d/additional-base-lib.conf
fi
true

EOF
chmod +x ./deb-contents/DEBIAN/postinst
echo
echo "build deb package:"
dpkg-deb -Z xz -b ./deb-contents "./additional-base-lib_${GLIBC_VERSION}-${ABL_VERSION}_${DEBIAN_DEB_ARCH}.deb"
# use gzip to compress for compatibility
check $?

echo
echo "complete with no error!"



mv -v ./additional-base-lib_${GLIBC_VERSION}-${ABL_VERSION}_${DEBIAN_DEB_ARCH}.deb ${STORE_APP_PATH}
popd

}


prepare
build
write_json $STORE_APP_PATH

rm -rf $WORKDIR
